package cn.com.yang.task;

import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.util.concurrent.Future;

/**
 * 定时任务线程池
 * TODO
 * @author yangyijin
 * @since 2024年1月26日-下午3:42:17
 */
public class MyScheduledThreadPoolExcutor extends ScheduledThreadPoolExecutor{
	private Logger logger = LoggerFactory.getLogger(getClass());
	public MyScheduledThreadPoolExcutor(int corePoolSize,ThreadFactory factory) {
		super(corePoolSize,factory);
	}
	
	@Override
	protected void beforeExecute(Thread t, Runnable r) {
		super.beforeExecute(t, r);
	}

	@Override
    protected void afterExecute(Runnable r, Throwable t) {
        super.afterExecute(r, t);
        // 打印异常信息
        this.printException(r, t);
    }

	private void printException(Runnable r, Throwable t) {
		if(t==null && r instanceof Future<?>) {
			try {
				Future<?> future = (Future<?>)r;
				if (future.isDone()) {
					Object obj = future.get();
					logger.info(obj.toString());
				}
			}catch (CancellationException ce) {
                t = ce;
            } catch (ExecutionException ee) {
                t = ee.getCause();
            } catch (InterruptedException ie) {
                Thread.currentThread().interrupt();
            }
		}
		if(t!=null) {
			logger.error(t.getMessage(),t);
		}
	}
}
